//
//  AWHomeController.swift
//  WeiBo
//
//  Created by AaronWei on 2017/6/4.
//  Copyright © 2017年 AaronWei. All rights reserved.
//

import UIKit
import YYModel

class AWHomeController: AWVisitorController {
    
    fileprivate lazy var homeViewModel: AWHomeViewModel = AWHomeViewModel()
    
    fileprivate lazy var pullUpView: UIActivityIndicatorView = {
        
        let indicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
        
        return indicatorView
        
    }()
    
    fileprivate lazy var pullDownView: AWRefreshControl = {
    
        let pullDown = AWRefreshControl()
        
        pullDown.addTarget(self, action: #selector(pullDownRefreshing), for: .valueChanged)
        
        return pullDown
    
    }()
    
    fileprivate lazy var tipLabel: UILabel = {
    
        let label = UILabel(title: "没有加载到最新微博数据", fontSize: 12, textColor: UIColor.white, maxWidth: nil)
        
        label.backgroundColor = UIColor.orange
        
        label.isHidden = true
        
        return label
    
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if !isLogin {
            
            visitorView?.updateView(message: nil, imageName: nil)
            
        } else {
            
            setupUI()
            
            loadData()
            
        }
        
    }
    
    private func setupUI() {
        
        self.navigationItem.title = AWUserAccountViewModel.sharedViewModel.userAccount?.name
        
        if let nav = self.navigationController {
            nav.view.insertSubview(tipLabel, belowSubview: nav.navigationBar)
            //  nav.navigationBar.frame.maxY 获取视图的最大y
            tipLabel.frame = CGRect(x: 0, y: nav.navigationBar.frame.maxY - 35, width: nav.navigationBar.width, height: 35)
        }
        
        setupTableView()
        
    }
    
    private func setupTableView() {
        
        tableView.backgroundColor = UIColor(white: 0.95, alpha: 1)
        
        tableView.register(AWHomeTableViewCell.self, forCellReuseIdentifier: HomeCellIdentifier)
        
        tableView.separatorStyle = .none
        
        tableView.rowHeight = UITableViewAutomaticDimension
        
        tableView.estimatedRowHeight = 200
        
        tableView.tableFooterView = pullUpView
        
        tableView.addSubview(pullDownView)
        
    }
    
    @objc fileprivate func pullDownRefreshing() {
                
        loadData()
        
    }
    
    fileprivate func endRefreshing() {
        
        pullUpView.stopAnimating()
        
        pullDownView.endRefreshing()
        
    }
    
    fileprivate func startTipAnimation(message: String) {
        
        if tipLabel.isHidden == false {
            return
        }
        
        tipLabel.isHidden = false
        
        tipLabel.text = message
        
        UIView.animate(withDuration: 2.0, animations: {
            
            self.tipLabel.transform = CGAffineTransform(translationX: 0, y: self.tipLabel.height)
            
        }) { (_) in
            
            UIView.animate(withDuration: 2.0, animations: {
                
                self.tipLabel.transform = CGAffineTransform.identity
                
            }, completion: { (_) in
                
                self.tipLabel.isHidden = true
                
            })
            
        }
        
    }
    
    fileprivate func loadData() {
        
        Thread.sleep(forTimeInterval: 1.0)
        
        homeViewModel.loadData(isUp: pullUpView.isAnimating) { (isSuccess: Bool, message: String) in
            
            if self.pullUpView.isAnimating == false {
                
                self.startTipAnimation(message: message)
                
            }
            
            self.endRefreshing()
            
            if isSuccess {
                
                self.tableView.reloadData()
                
            }
            
        }
//
//        let token = AWUserAccountViewModel.sharedViewModel.userAccount?.access_token
//        
//        AWNetworkTools.sharedTools.requestStatuses(token: token!) { (responseObject, error) in
//            
//            if error != nil {
//                
//                print(error!)
//                
//                return
//                
//            }
//            
//            let dict = responseObject as! [String: Any]
//            
//            let statusesDicArray = dict["statuses"] as! [[String: Any]]
//            
////            var tempArray = [AWStatusesModel]()
////            
////            for statusesDic in statusesDicArray {
////                
////                let model = AWStatusesModel(dict: statusesDic)
////                
////                tempArray.append(model)
////                
////            }
//            
//            let modelArray = NSArray.yy_modelArray(with: AWStatusesModel.self, json: statusesDicArray) as! [AWStatusesModel]
//            
//            self.statusesArray = modelArray
//            
//            self.tableView.reloadData()
//            
//        }
//        
    }
    
}

extension AWHomeController {
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return homeViewModel.statusesArray.count
        
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: HomeCellIdentifier, for: indexPath) as! AWHomeTableViewCell
                
        cell.homeStatusesViewModel = homeViewModel.statusesArray[indexPath.row]
        
        return cell
        
    }
    
    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        if indexPath.row == homeViewModel.statusesArray.count - 1 && !pullUpView.isAnimating {
            
            pullUpView.startAnimating()
            
            loadData()
            
        }
        
    }
    
}
